package com.reggie.module.controller;

import com.reggie.common.ResultResponseVo;
import com.reggie.module.entity.po.Dish;
import com.reggie.module.mapper.DishMapper;
import com.reggie.module.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 早睡蛋
 * @Date 2022/9/25 21:06:22
 * @Desc:
 *      定时任务：
 *          用于删除文件中多余的图片
 */
@Configuration
@EnableScheduling
public class ScheduledController {

    @Value("${dishImages.dir}")
    private String dishImages;

    @Autowired
    private DishMapper dishMapper;


    @Scheduled(cron = "0 0 3 * * ?")
    private void configureTasks() {
        //遍历数据库，获取所有图片路径信息
        List<String> imageList = dishMapper.getImage();
        //创建哈希map，用于存放图片信息
        Map<String, Integer> imageMap = new HashMap<>();
        //遍历图片集合，删除前缀
        for (String s : imageList) {
            s = s.substring(11);
            System.out.println(s);
            //向imageMap中存放信息
            imageMap.put(s, 1);
        }
        //遍历文件夹下的图片，判断是否存在imageMap中，不存在则删除图片文件
        File dir = new File(dishImages);
        File[] files = dir.listFiles(); //获取文件夹中的所有文件
        for (File file : files) {
            String fileName = file.getName();
            Integer flag = imageMap.get(fileName);
            if (flag == null) {
                file.delete();
            }
        }
    }


}
